import { Inject, Injectable } from '@angular/core';
import { BaseService } from '@core/routes-services/base.service';
import { CacheService } from '@core/routes-services/cache.service';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { CurrUserService } from '@core/routes-services/Observer-service/curr-user.service';
import { CurrUserModel } from '@core/routes-services/Observer-service/curr-user.model';
import { MenuService } from '@delon/theme';

/**
 * 登录服务
 */
@Injectable()
export class LoginService extends BaseService {

  router: Router;

  constructor(http: HttpClient, cacheService: CacheService, router: Router,
              private menuService: MenuService,
              private currUserService: CurrUserService,
              @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {
    super(http, cacheService);
    this.router = router;
  }


  /**
   * 登录
   *
   * @param user
   * @returns {Promise<any>}
   */
  login(user): Promise<any> {
    const url = 'auth/login'; // 此次接口路径修改注意修改baseService中post方法特殊处理点,也可将次接口配置成字典方式处理
    const resultPromise = this.post(url, user);
    return resultPromise;
  }

  logout(): Promise<any> {
    const url = 'auth/logout';
    const resultPromise = this.post(url, null);
    resultPromise.then((res) => {
      this.tokenService.clear();
      this.cacheService.clear();
      this.router.navigateByUrl(this.tokenService.login_url);
    }, error => {
      this.tokenService.clear();
      this.cacheService.clear();
      this.router.navigateByUrl(this.tokenService.login_url);
    });
    return resultPromise;
  }

  /**
   * 获取当前登录用户基础信息
   * @returns {Promise<any>}
   */
  getCurrUserInfo(): Promise<any> {
    const url = 'api/users/curr_user';
    const resultPromise = this.get(url);
    resultPromise.then((res) => {
      this.cacheService.setCurrUserInfo(res.data);
      this.currUserService.setCurrUser(new CurrUserModel(res.data.id, res.data.name, res.data.role));
    });
    return resultPromise;
  }

  /**
   * 缓存基础配置和变更性小的数据缓存之
   *
   * @returns {Promise<any>}
   */
  initAppInfo(): Promise<any> {
    const url = 'api/base/info';
    const resultPromise = this.get(url);
    resultPromise.then((res) => {
      this.cacheService.setCurrUserInfo(res.data.userInfo);
      this.currUserService.setCurrUser(new CurrUserModel(res.data.userInfo.id, res.data.userInfo.name, res.data.userInfo.role));
      this.cacheService.setAgentLevel(res.data.agentLevelsList);
      this.cacheService.setGoodsClass(res.data.goodsClassList);
      this.cacheService.setDistrict(res.data.salesmanDistrictList);
      this.cacheService.setMarketAgentLevel(res.data.marketAgentLevelsList);
      this.cacheService.setActivityProducts(res.data.activityProductsList)
    });
    return resultPromise;
  }

}
